import { createSlice } from "@reduxjs/toolkit";
import axios from "axios";


const foodsStore = createSlice({
    name: "foods",
    initialState: {
        // 菜单列表
        foodsList: [],
        // 菜单激活下标值
        activeIndex: 0,
        // 购物出列表
        cartList: [],
    },
    reducers: {
        setFoodsList(state, action) {
            state.foodsList = action.payload;
        },
        changeActiveIndex(state, action) {
            state.activeIndex = action.payload;
        },
        addCart(state, action) {
            const item = state.cartList.find(item => item.id === action.payload.id)
            if (item) {
                item.count++
            } else {
                state.cartList.push(action.payload)
            }
        },
        // 添加
        increaseCount(state, action) {
            const item = state.cartList.find(item => item.id === action.payload.id)
            item.count++
        },
        // 减少
        decreaseCount(state, action) {
            const item = state.cartList.find(item => item.id === action.payload.id)
            if(item.count === 0){
                return
            }else{
                item.count--
            }
        },
        // 清除
        clearCart(state) {
            state.cartList = []
        }
    }
})

// 异步获取数据
const { setFoodsList, changeActiveIndex, addCart, increaseCount, decreaseCount,clearCart } = foodsStore.actions;
const fetchFoodsList = () => {
    return async (dispatch) => {
        const res = await axios.get("http://localhost:3008/foodData")
        dispatch(setFoodsList(res.data))
    }
}

export { fetchFoodsList, changeActiveIndex, addCart, increaseCount, decreaseCount,clearCart }
const reducer = foodsStore.reducer;
export default reducer;
